const errcode = require('../utils/errcode')
const logger = require('../utils/logger')
const exception = require('../utils/exception')

module.exports = async function (ctx, next) {
    ctx.success = function (data) {
        ctx.body = {
            ...errcode.OK,
            data
        }
    }

    ctx.error = function (err, data) {
        ctx.body = {
            ...err,
            data
        }
    }

    ctx.login = ctx.session.user

    try {
        await next()
    } catch (err) {
        logger.error(err)

        if (err instanceof exception.ResourceRemoveError) {
            ctx.error(errcode.RESOURCE_RELATED, err.message)
        } else {
            ctx.error(errcode.UNKNOWN, err.message)
        }
    }
}
